package com.sprite.utils.io;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Jack
 */
public class ByteBuffer {

    private List<byte[]> buffer = new ArrayList<>();

    private int paceSize = 512;    // 每个分区的大小

    private int length;            // 总长度

    private byte[] _this;        // 当前分区
    private int _thisIndex = -1;    // 当前数据下标


    public ByteBuffer() {
        extend();
    }

    public ByteBuffer(int paceSize) {
        this.paceSize = paceSize;
        extend();
    }


    public void append(byte[] bts) {
        length += bts.length;

        for (byte bt : bts) {
            append(bt);
        }
    }

    public void append(byte[] bts, int length) {
        if (length > bts.length) {
            throw new IndexOutOfBoundsException();
        }

        int index = 0;
        while (index < length) {
            append(bts[index++]);
        }
    }

    public int size() {
        return length;
    }

    public byte[] toByteArray() {
        int index = 0;
        int thisLength  = _thisIndex+1;
        byte[] bys = new byte[length];

        int size = buffer.size();

        for (int i = 0; i < size - 1; i++) {
            byte[] temp = buffer.get(i);
            for (byte bt : temp) {
                bys[index++] = bt;
            }
        }


        while (index < length) {
            bys[index++] = _this[thisLength - (length - index)];
        }

        return bys;
    }

    private void append(byte bt) {
        length++;

        if (_thisIndex == paceSize - 1) {
            extend();
        }

        _this[++_thisIndex] = bt;
    }

    private void extend() {
        _this = new byte[paceSize];
        buffer.add(_this);
        _thisIndex = -1;
    }
}
